package sk.velkavrana.app.databaseInfo.dao.xml;

import sk.velkavrana.app.databaseInfo.dao.AbstractDao;
import sk.velkavrana.app.databaseInfo.model.StorableObject;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author mtymes
 * @since Sep 22, 2009 2:48:01 AM
 */
public abstract class AbstractDaoXml<T extends StorableObject<I>, I> implements AbstractDao<T, I> {

    protected String directoryPath;


    protected abstract T getFromXml(String fileName);


    protected String getFullFileName(I fileName) {
        return getDirectoryPath() + File.separator + fileName + ".xml";
    }


    public List<T> getAll() {
        List<T> beans = new ArrayList<T>();

        File dir = new File(getDirectoryPath());

        if (dir.exists() && dir.isDirectory()) {
            FileFilter fileFilter = new FileFilter() {
                public boolean accept(File pathname) {
                    if (pathname.isDirectory()) {
                        return false;
                    }

                    String[] splits = pathname.getAbsolutePath().split("\\.");

                    return "xml".equalsIgnoreCase(splits[splits.length - 1]);
                }
            };

            for (File fileName : dir.listFiles(fileFilter)) {
                T bean = getFromXml(fileName.getAbsolutePath());

                if (bean != null) {
                    beans.add(bean);
                }
            }
        }

        return beans;
    }


    public T getById(I id) {
        return getFromXml(getFullFileName(id));
    }


    public void remove(T bean) {
        File file = new File(getFullFileName(bean.getId()));

        if (file.exists() && file.isFile()) {
            file.delete();
        }
    }


    public String getDirectoryPath() {
        return directoryPath;
    }


    public void setDirectoryPath(String directoryPath) {
        this.directoryPath = directoryPath;
    }

}
